<?php
/**
 * 初始化商家的库存信息
 * User: chenjunliang@star-net.cn
 * Time: 2017/10/31 9:57
 */

namespace app\console\swooletask\logic;


use app\console\swoole\model\Inventory;
use app\console\swoole\model\InventoryRemain;
use app\console\swoole\model\PositionType;
use app\console\swoole\model\SupportSaleCompany;
use app\index\model\Position;
use think\Db;
use think\Log;

class InitCompany {


    /**
     * 商家库存
     * @param $data
     * @return array|bool
     */
    public function initCompanyInventory($data) {

        if(!$data) {
            $ret = [
                'type'    => 'initCompanyInventory',
                'status'  => false,
                'message' => 'data is empty'
            ];
            $this->_log($ret);

            return false;
        }

        $invoModel    = new Inventory();
        $companyModel = new SupportSaleCompany();

        $companycode = $data['companycode'];
        $position    = $data['position'];
        Db::startTrans();
        foreach($position as $po) {
            $invoInfo[] = [
                'in_companycode'          => $companycode,
                'in_position_correlation' => $po['correlation'],
                'in_init_status'          => 0,
                'in_ctime'                => date('Y-m-d H:i:s', time())
            ];
        }
        //插入库存
        $addin = $invoModel->addInventory($invoInfo);

        if(!$addin) {
            Db::rollback();
            $ret = [
                'type'    => 'initCompanyInventory',
                'status'  => false,
                'message' => 'insert fail'
            ];
            $this->_log($ret);

            return false;
        }

        //更新初始化状态
        $up = $companyModel->updateInitByCompanycode($companycode);

        if(!$up) {
            Db::rollback();
            $ret = [
                'type'    => 'initCompanyInventory',
                'status'  => false,
                'message' => 'update status fail'
            ];
            $this->_log($ret);

            return false;
        }
        Db::commit();


        $ret = [
            'type'        => 'initCompanyInventory',
            'status'      => true,
            'companycode' => $companycode,
            'message'     => 'success'
        ];
        $this->_log($ret);

    }

    private function _log($log) {
        Log::record(json_encode(['swoole_server' => $log]), 'elk_more_info','init_company');
        //Log::save();
    }
}